//
//  ApiLogin.m
//  clublbiza
//
//  Created by WANG TOM on 7/21/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ApiLogin.h"
#import "ASIHTTPRequest.h"
#import "JSON.h"
#import "clublbizaAppDelegate.h"


static ApiLogin *_shareInstance = nil;
@implementation ApiLogin
@synthesize session_id;
@synthesize totalDownloadVideoCount;
@synthesize isBusySyncThread;
@synthesize completedSync;
+ (ApiLogin *) shareInstance
{
    @synchronized(self){
        if(_shareInstance == nil)
        {
            _shareInstance = [[self alloc] init];
            [_shareInstance login];
        }
        return _shareInstance;
    }
}
- (id)init {
	if (self = [super init]) {
		self.session_id = nil;
        self.totalDownloadVideoCount = 0;
        self.isBusySyncThread = FALSE;
        self.completedSync = FALSE;
	}
	return self;
}
-(void) dealloc {
    [self.session_id dealloc];
    [super dealloc];
}

-(void) login
{
    AppMain *appMain = [AppMain shareInstance];
    NSURL *url = [NSURL URLWithString:[[appMain getGateWayURL:NO] stringByAppendingFormat:@"a=login&uname=%@&upass=%@&key=%@",API_USER,API_USER_PASSWORD,API_KEY]];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response_str = [request responseString];
        id response_obj = [response_str JSONValue];
        if([response_obj isKindOfClass:[NSDictionary class]]){
            id error_obj = [response_obj objectForKey:@"error"];
            if([error_obj length] == 0){
                self.session_id = [response_obj objectForKey:@"data"];
            }else{
                NSException* exception = [NSException
                                          exceptionWithName:@"SERVER_ERROR"
                                          reason:error_obj
                                          userInfo:nil];
                @throw exception;
            }
        } else{
            NSException* exception = [NSException
                                      exceptionWithName:@"SERVER_ERROR"
                                      reason:@"服务器内部错误"
                                      userInfo:nil];
            @throw exception;
        }
       
    } else{
        
        if ( error.code == 2 )
        {
            NSException* exception = [NSException
                                        exceptionWithName:@"CONNECT_ERROR"
                                        reason:@"不能够连接服务器"
                                        userInfo:nil];
            @throw exception;
        } else {
            NSException* exception = [NSException
                                      exceptionWithName:@"CONNECT_ERROR"
                                      reason:[error localizedDescription]
                                      userInfo:nil];
            @throw exception;
        }
    }
}
-(void) testGateWay:(NSString*)gateWayUrl
{
    NSURL *url = [NSURL URLWithString:[gateWayUrl stringByAppendingFormat:@"/api.php?a=login&uname=%@&upass=%@&key=%@",API_USER,API_USER_PASSWORD,API_KEY]];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response_str = [request responseString];
        id response_obj = [response_str JSONValue];
        if([response_obj isKindOfClass:[NSDictionary class]]){
            id error_obj = [response_obj objectForKey:@"error"];
            if([error_obj length] == 0){
                self.session_id = [response_obj objectForKey:@"data"];
            }else{
                NSException* exception = [NSException
                                          exceptionWithName:@"SERVER_ERROR"
                                          reason:error_obj
                                          userInfo:nil];
                @throw exception;
            }
        } else{
            NSException* exception = [NSException
                                      exceptionWithName:@"SERVER_ERROR"
                                      reason:@"服务器内部错误"
                                      userInfo:nil];
            @throw exception;
        }
        
    } else{
        
        if ( error.code == 2 )
        {
            NSException* exception = [NSException
                                      exceptionWithName:@"CONNECT_ERROR"
                                      reason:@"不能够连接服务器"
                                      userInfo:nil];
            @throw exception;
        } else {
            NSException* exception = [NSException
                                      exceptionWithName:@"CONNECT_ERROR"
                                      reason:[error localizedDescription]
                                      userInfo:nil];
            @throw exception;
        }
    }
}
-(NSArray *) syncList
{
    NSArray *sync_list = nil;
    ApiLogin *apiLogin = [ApiLogin shareInstance];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    

    NSInteger v_beverage = [userDefaults integerForKey:@"tbl_current_version_Beverag"];
     NSInteger v_beverage_item = [userDefaults integerForKey:@"tbl_current_version_Beverag_item"];
    NSInteger v_food = [userDefaults integerForKey:@"tbl_current_version_Food"];
    NSInteger v_food_item = [userDefaults integerForKey:@"tbl_current_version_Food_item"];
    
    NSInteger v_ibizatv = [userDefaults integerForKey:@"tbl_current_version_Ibizatv"];
    NSInteger v_resource = [userDefaults integerForKey:@"tbl_current_version_Resource"];
    NSInteger v_delete = [userDefaults integerForKey:@"tbl_current_version_delete_record_log"];
    
    AppMain *appMain = [AppMain shareInstance];
    
    NSURL *url = [NSURL URLWithString:[[appMain getGateWayURL:NO] stringByAppendingFormat:@"a=need_sync_list&sid=%@&v_beverage=%d&v_beverage_item=%d&v_food=%d&v_food_item=%d&v_video=%d&v_resource=%d&v_delete=%d",apiLogin.session_id,v_beverage,v_beverage_item,v_food,v_food_item,v_ibizatv,v_resource,v_delete]];
	ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        NSString *response_str = [request responseString];
        id response_obj = [response_str JSONValue];
        if ( nil != response_obj) {
            sync_list = [response_obj objectForKey:@"data"];
        }
    }else{
        NSLog(@"%@",error);
    }
    return sync_list;
}
-(Boolean) hasLogin{
    return self.session_id != nil;
}
-(NSManagedObjectContext *) getCoreDataContext
{
    clublbizaAppDelegate *appDelegate = (clublbizaAppDelegate *)[[UIApplication sharedApplication] delegate];
    return appDelegate.managedObjectContextBkThread;
}

@end
